<template>
    <div class="meeting">
        <!-- 标准表格 stripe-->
        <el-table ref="standardTable"
        class="w-table"
         :class="{'w-table_moving':dragState.dragging}"
            :loading="loading"
            :maxHeight="maxHeight"
            :row-class-name="tableRowClassName"
            :row-key="getRowKeys"
            border
            :stripe='stripe' 
            :cell-class-name="cellClassName" 
            :header-cell-class-name="headerCellClassName"
            :data="props_data" 
            :tooltip-effect="tooltip" 
            @row-click="chooseone"
            @current-change="handleCurrentChange"
            @selection-change="handleSelectionChange"  @sort-change="sortChangeTable">
            <slot name="table_before"/>
            <template v-for="(item,index) in tableHeader">
                <!-- 表头全选 -->
                <el-table-column show-overflow-tooltip v-if="item.type=='selection'" :fixed="item.fixed" :align="item.align" :key="index" :width="item.width" :type="item.type"></el-table-column>
                <!-- 单选 -->
                <el-table-column show-overflow-tooltip v-if="item.type=='radio'" :fixed="item.fixed" :align="item.align" :key="index" :width="item.width" :type="item.type">
                    <template slot-scope="scope">
                        <el-radio v-model="radio" :label="scope.row.id">
                            <span class="el-radio__label"></span>
                        </el-radio>
                    </template>
                </el-table-column>
                <!-- 自定义数据字典转换 -->
                 <el-table-column show-overflow-tooltip v-if="item.type=='dictionary'" :fixed="item.fixed" :column-key="index.toString()"
                
                :formatter="typeFormatter" :align="item.align" :key="index" :prop="item.prop" :label="item.label" :width="item.width"
                ></el-table-column>
                <!-- 柱状图 -->
                <el-table-column show-overflow-tooltip v-if="item.type=='echartsColumn'" :fixed="item.fixed" :column-key="index.toString()"
                 :align="item.align" :key="index" :prop="item.prop" :label="item.label" :width="item.width"
                >
                    
                </el-table-column>
                <!-- 普通列 -->
                <el-table-column show-overflow-tooltip v-if="item.type==''" :fixed="item.fixed"
                  :column-key="index.toString()"  :align="item.align" :key="index" :prop="item.prop" :label="item.label" 
                :width="item.width" :sortable="item.isSortable">
                </el-table-column>
            </template>
            <slot name="table_after"/>
        </el-table>
        <!--分页-->
        <!-- <el-pagination
            v-if="isTable"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
            style="text-align: right;margin:10px 0;"
            :current-page="props_pageNo"
            :page-size="pageSize"
            :page-sizes="pageSizeOpt"
            :total="props_total"
            layout="total, sizes, prev, pager, next, jumper">
        </el-pagination> -->
        <pagingModule :props_total="props_total" :isTable="isTable" :props_pageNo="props_pageNo" :pageSize="pageSize" :pageSizeOpt="pageSizeOpt"  @pageBefore="handleBefore" :isSmall="true"></pagingModule>
    </div>
</template>
<script>
    import EchartsTemplate from "../echartsTemplate/echartsPillar";
    import pagingModule from "../pagingModule";
    export default {
        name: "StandardTable",
        props: {
            id:String,
            url:String,
            apiName: Function,
            tooltip:String,//dark
            columns: {
                type: Array,
                default: () => []
            },
            tableData: {
                type: Array,
                default: () => []
            },
            stripe: {
                type: Boolean,
                default: false
            },
            pageSizeOpt:{
                type: Array,
                default() {
                    return [10, 20, 30, 50, 100];
                }
            },
            pageNum: {
                type: Number,
                default: 1
            },
            pageSize: {
                type: Number,
                default: 10,
            },
            maxHeight: {
                type: Number,
                default: 2000
            },
            tableRowClassName:{
                type: Function,
            },
        },
        components: {
            EchartsTemplate,
            pagingModule
        },
        data() {
            return {
                currentSelectItem:{},
                radio:null,
                hasChildren:true,
                tableHeader: this.columns,
                // 拖拽列
                dragState: {
                    start: -9, // 起始元素的 index
                    end: -9, // 移动鼠标时所覆盖的元素 index
                    dragging: false, // 是否正在拖动
                    direction: undefined // 拖动方向
                },
                isTable:true,
                loading:false,
                props_data: [],
                props_total: 0,
                props_pageNo: this.pageNum,
                props_query: {
                    pageNum: this.pageNum,
                    pageSize: this.pageSize
                },
                saveData:[],
                rowNum:1,
                checkedDetail:[],//tab表格选中的数据(包括跨页缓存)
                formatterList:{
                    "sex":[{"value":1,"type":"男"},{"type":"女","value":0}],
                    "IS_MARRY":[{isMarry:1,name:"是"},{isMarry:0,name:"否"}],
                    "STATE":[{"state":0,"type":'提交'},{"state":1,"type":'审核中'},{"state":2,"type":'已通过'},{"state":3,"type":'已拒绝'}],
                    "LEVEL":[{"level":"1","type":"一级"},{"level":"2","type":"二级"},{"level":"3","type":"三级"}]
                },
            }
        },
        watch: {
            columns (val, oldVal) {
                this.tableHeader = val
            },
            props_data(val,oldVal){
                this.props_data = val;
            }
        },
        created(){
            this.saveDataInit();
        },
        methods: {
            handleCurrentChange(row) {
                this.currentSelectItem = row;
                this.$emit("handleCurrentChange",row)
            },
            chooseone(row){
                this.radio = row.id
            },
            getRowKeys(rows){
                return rows[this.id];
            },
            // 拖拽列置换
            /*******开始**********/
            renderheader(h, { column, $index },formatterObject,propString,formatterArrayString){
                column.formatterArray = formatterObject?formatterObject:this.formatterList[formatterArrayString];//
                column.propString = propString?propString:[]; //转换后字段名
                // column.filterType = filterType?filterType:""; //判断是自定义转换customDictionary还是数据字典转换dictionary
                return h('div',{
                        'class': ['thead-cell'],
                        on: {
                            mousedown: ($event) => { this.handleMouseDown($event, column) },
                            mousemove: ($event) => { this.handleMouseMove($event, column) }
                        }
                    }, [
                        // 添加 <a> 用于显示表头 label
                        h('a',{}, column.label),
                        // 添加一个空标签用于显示拖动动画
                        // createElement('span', {
                        //     'class': ['virtual']
                        // })
                    ])
            },
            // 按下鼠标开始拖动
            handleMouseDown (e, column) {
                this.dragState.dragging = true
                this.dragState.start = parseInt(column.columnKey)
                // 给拖动时的虚拟容器添加宽高
                let table = document.getElementsByClassName('w-table')[0]
                let virtual = document.getElementsByClassName('virtual')
                for (let item of virtual) {
                    item.style.height = table.clientHeight - 1 + 'px'
                    item.style.width = item.parentElement.parentElement.clientWidth + 'px'
                }　
                document.addEventListener('mouseup', this.handleMouseUp);
            },
            // 鼠标放开结束拖动
            handleMouseUp () {
                this.dragColumn(this.dragState)
                // 初始化拖动状态
                this.dragState = {
                    start: -9,
                    end: -9,
                    dragging: false,
                    direction: undefined
                }　
                document.removeEventListener('mouseup', this.handleMouseUp);
            },
            // 拖动中
            handleMouseMove (e, column) {
                if (this.dragState.dragging) {
                    let index = parseInt(column.columnKey) // 记录起始列
                    if (index - this.dragState.start !== 0) {
                        this.dragState.direction = index - this.dragState.start < 0 ? 'left' : 'right' // 判断拖动方向
                        this.dragState.end = parseInt(column.columnKey)
                    } else {
                        this.dragState.direction = undefined
                    }
                }else{
                    return false
                }
            },
            // 拖动易位
            dragColumn ({start, end, direction}) {
                let tempData = []
                let left = direction === 'left'
                let min = left ? end : start - 1
                let max = left ? start + 1 : end
                for (let i = 0; i < this.tableHeader.length; i++) {
                    if (i === end) {
                        tempData.push(this.tableHeader[start])
                    } else if (i > min && i < max) {
                        tempData.push(this.tableHeader[ left ? i - 1 : i + 1 ])
                    } else {
                        tempData.push(this.tableHeader[i])
                    }
                }
                this.tableHeader = tempData
            },
            headerCellClassName (column, columnIndex) {
                let active = columnIndex - 1 === this.dragState.end ? `darg_active_${this.dragState.direction}` : ''
                let start = columnIndex - 1 === this.dragState.start ? `darg_start` : ''
                return `${active} ${start}`
            },
            cellClassName (column, columnIndex) {
                return (columnIndex - 1 === this.dragState.start ? `darg_start` : '')
            },
            /*******结束**********/
            //查询
            query(arg) {
                let that = this;
                this.loading = true;
                let param = {};
                if(arg && arg.pageNum){
                    param.pageNum = arg.pageNum;
                }
                Object.assign(param,arg)
                let apiName = that.apiName;
                if(!apiName){
                    that.props_data = that.tableData ? that.tableData : [];
                    that.saveData = that.tableData ? [...that.tableData] : [];
                    that.saveDataInit();
                    return;
                }
                // debugger
                apiName(param).then(res => {
                // axios.post(url,param).then(res => {
                    that.loading = false;
                    res = res && res.rspBody ? res.rspBody : {}
                    if(JSON.stringify(res) == '{}'){
                        console.log('11')
                        // that.props_data = []
                        // that.saveData = []
                        // debugger
                        // 为了测试跨页缓存
                        if(arg.pageNum == 2){
                            let table = [{id:18,"classificationStr":"劳保/安全/消防 - 呼吸防护 - 电动送风呼吸防护系统","commodityTypeId":"10003","level":3,"levelDesc":"可以上","echartsColumn":{seriesData:[{name: '邮件营销',type: 'line',stack: '总量',data: [120, 132, 101, 134, 90, 230, 210]}],seriesType:"line"}},
                            {id:19,"classificationStr":"劳保/安全/消防 - 呼吸防护 - 一次性口罩","commodityTypeId":"10001","level":2,"levelDesc":"可以上","echartsColumn":{seriesData:[{name: '邮件营销',type: 'line',stack: '总量',data: [120, 132, 101, 134, 90, 230, 210]}],seriesType:"line"}},
                            {id:20,"classificationStr":"劳保/安全/消防 - 呼吸防护 - 防护面具及配件","commodityTypeId":"10002","level":1,"levelDesc":"可以上","echartsColumn":{seriesData:[{name: '邮件营销',type: 'line',stack: '总量',data: [120, 132, 101, 134, 90, 230, 210]}],seriesType:"line"}},]
                                that.props_data = table;
                                that.saveData = table;
                                that.props_total = 13;
                                that.props_pageNo = that.pageNum || 1;
                                that.saveDataInit();
                                return;
                        }
                        that.props_data = that.tableData//暂时 只是为了效果展示
                        that.saveData = that.tableData ? [...that.tableData] : [];//暂时 只是为了效果展示
                        that.props_pageNo = that.pageNum || 1;//暂时 只是为了效果展示
                        that.props_total = that.tableData.length;//暂时 只是为了效果展示
                        that.saveDataInit();//暂时 只是为了效果展示
                        return 
                    }
                    res.resultData = res.resultData ? res.resultData : []
                    that.props_data = res.resultData;
                    that.props_pageNo = res.pageNum || 1;
                    that.props_total = res.total ? res.total :0;
                    that.saveDataInit();
                    that.$emit('queryResult', res);
                });
            },
            handleBefore(pageArr) {
                if(pageArr.pageType=="size"){
                    this.query({
                        pageNum:1,
                        pageSize:pageArr.pageSize
                    });
                }else{
                    var changeFlag = false;
                    for(var i=0;i<this.saveData.length;i++){
                        if(this.saveData[i].opt&&this.saveData[i].opt == "insert"||this.saveData[i].opt == "update"||this.saveData[i].opt == "delete"){
                            changeFlag = true;
                            break;
                        }
                    }
                    if(changeFlag){
                        this.$alert("请先保存修改再切换分页", "提示");
                        return false;
                    }
                    this.query({
                        pageNum:pageArr.page
                    });
                }
                // 
            },
            // 初始化数据
            saveDataInit(){
                for(var i=0;i<this.props_data.length;i++){
                    this.props_data[i].rowNum = this.rowNum;
                    this.rowNum++;
                }
                this.saveData = [...this.props_data];
            },
            // handleAfter(size){
            //     debugger;
            //     this.isPage=false;
                
            // },
            // 勾选的的数据
            handleSelectionChange(selection) {
                this.checkedDetail = selection;
                console.log(selection);
                this.$emit('selectionChange', selection);
            },
            // 小代码转换
            typeFormatter(row, column){
                for (var i in column.formatterArray) {
                    if (row[column.propString] == column.formatterArray[i][column.propString]){
                        row = Object.assign(row,column.formatterArray[i]);
                    }
                }
                // console.log(row);
                return row[column.property];
            },      
            //排序
            sortChangeTable(column){
                this.$emit("sortChangeTableAfter",column);
                if(column.column.sortable=="custom"){
                    var fieldName = column.prop;
                    var sortingType = column.order;
                    //按照降序排序
                    if(sortingType == "descending"){
                        // sid asc desc
                        this.query({
                            order : fieldName+ " desc"
                        });
                    }
                    //按照升序排序
                    else{
                        this.query({
                            order : fieldName+ " asc"
                        });
                    }
                }
            },
        }
    };
</script>
<style>
/* lang="less"  */
.meeting{
    width: 100%;
    margin-top: 10px;
}
.el-table{
    overflow:auto;
}
.el-table .el-table__header th{
    background-color:#f8f8f9;
    color:#515a6e;
}
.el-table td, .el-table th {
    padding:8px 0;
    
}
.w-table .el-table .darg_start { background-color: #f3f3f3; }

.w-table .el-table th { padding: 0; }

.w-table .el-table th .virtual { position: fixed; display: block; width: 0; height: 0; margin-left: -10px; background: none; border: none; }

.w-table .el-table .darg_active_left { border-left: 2px dotted #666; z-index: 99; }

.w-table .el-table .darg_active_right { border-right: 2px dotted #666; z-index: 99; }

.w-table .thead-cell { padding: 0; display: inline-flex; flex-direction: column; align-items: left; cursor: pointer; overflow: initial; }

.w-table .thead-cell:before { content: ""; position: absolute; top: 0; left: 0; bottom: 0; right: 0; }

.w-table.w-table_moving .el-table th .cell .thead-cell { cursor: move !important;}

.w-table.w-table_moving .el-table__fixed { cursor: not-allowed; }

.el-table .warning-row {
    background: #FFF;
}
.el-table .success-row {
    background: #f0f9eb;
}
</style>